package TCPEcho;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TCPEchoSever2 {
    private ServerSocket socket = null;

    public TCPEchoSever2(int port) throws IOException {
        socket = new ServerSocket(port);
    }

    public void start() throws IOException {
        while(true){
            Socket clineSocket = socket.accept();
            Thread t = new Thread(()->{
                try {
                    processConetion(clineSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
    }

    private void processConetion(Socket clineSocket) throws IOException {
        System.out.printf("[%s:%d],客户端上线！\n",clineSocket.getInetAddress(),clineSocket.getPort());
        try(InputStream inputStream = clineSocket.getInputStream();
            OutputStream outputStream = clineSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true){
                if(!scanner.hasNext()){
                    System.out.printf("[%s:%d],客户端下线！\n",clineSocket.getInetAddress(),clineSocket.getPort());
                    break;
                }
                //读取客户端的请求
                String request = scanner.next();
                //根据请求返回响应
                String response = process(request);
                //将响应返回给客户端
                writer.println(response);
                //清空缓冲区
                writer.flush();
                //打印日志
                System.out.printf("[%s:%d] req:%s resp:%s\n",clineSocket.getInetAddress(),clineSocket.getPort(),request,response);
            }
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoSever2 tcpEchoSever2 = new TCPEchoSever2(8080);
        tcpEchoSever2.start();
    }
}
